package com.leyou.gateway.filter;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.scheduled.AppTokenScheduled;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AppTokenScheduled appTokenScheduled;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request域
        ServerHttpRequest request = exchange.getRequest();
        //获取response域
        ServerHttpResponse response = exchange.getResponse();
        //获取当前请求的url地址 /api/auth/login
        String url = request.getURI().getPath();
        //判断当前url地址，如果不需要登录直接放行
        if(isAllowPath(url)){
            //继续执行其他过滤器
            return chain.filter(exchange);
        }
        //给转发请求的请求头中添加网关服务器的token信息
        request.mutate().header(LyConstants.APP_TOKEN_HEADER, appTokenScheduled.getToken()).build();
        //获取token
        String token = request.getCookies().getFirst(jwtProp.getCookie().getCookieName()).getValue();
        //判空
        if(StringUtils.isEmpty(token)){
            //阻止继续向下访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            //阻止继续向下访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //判断当前token是否在黑名单
        if(redisTemplate.hasKey(payload.getId())){
            //阻止继续向下访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //获取当前用户的id
        Long userId = payload.getUserInfo().getId();
        //把用户id放入请求头中
        request.mutate().header(LyConstants.USER_HOLDER_KEY, userId.toString()).build();
        //继续执行其他过滤器
        return chain.filter(exchange);
    }

    private boolean isAllowPath(String url) {
        //获取所有白名单路径并遍历
        for (String allowPath : filterProp.getAllowPaths()) {
            if(url.startsWith(allowPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
